﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MeTalker.Aide.data;
using MeTalker.Aide.DBUtility;
using MeTalker.Aide.Forms.Mode;
using MeTalker.Aide.Forms;
using MeTalker.Aide.Mode;

namespace MeTalker.Aide
{
    internal class GuideBase : ServiceBase
    {
        internal IDictionary<string, string> dictUsers = new Dictionary<string, string>();
        internal IDictionary<string, int> dictUsersError = new Dictionary<string, int>();

        internal MessageNode Menu { get; set; }
        const string EXIT_MENU = "123";
        const string BACK_MENU = "0";
        const string BACK_MAIN_MENU = "100";
        const string CUSTOM_MSG = "321";
        int MenuId = 0;
        ProcInfo proc;

        internal GuideBase(ProcInfo proc) {
            this.proc = proc;
        }

        string GetBackMenu(string name, string msg)
        {
            try
            {
                if (dictUsers.ContainsKey(name))
                {
                    string cmd = dictUsers[name];
                    cmd = cmd.Substring(0, cmd.LastIndexOf(","));
                    try
                    {
                        if (cmd.Equals("-1"))
                        {
                            return GetGreetings();
                        }
                        else
                        {
                            string[] cmds = cmd.Split(',');
                            Node node = GetNode(Menu.Nodes, int.Parse(cmds[1]));
                            Node temp = GetParentNode(node, cmds);
                            return GetMenuMessage(temp);
                        }
                    }
                    finally
                    {
                        dictUsers[name] = cmd;
                    }
                }
                else
                {
                    return GetGreetings();
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("", ex);
                return string.Empty;
            }
        }

        string ExitMenu(string name) {
            if (dictUsers.ContainsKey(name))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("");
                sb.AppendLine("已经退出导购菜单。若要留言，请继续回复！");
                sb.AppendLine("若要再次查看导购菜单，请回复" + CUSTOM_MSG);
                sb.AppendLine("");
                dictUsers[name] = "" + EXIT_MENU;
                if (dictUsersError.ContainsKey(name)) {
                    dictUsersError.Remove(name);
                }
                return sb.ToString();
            }
            return string.Empty;
        }

        internal string FindMenuMessage(string name, string time, string msg)
        {
            string response = string.Empty;
            try
            {
                #region 处理指令
                switch (msg)
                {
                    case CUSTOM_MSG:
                        {
                            if (dictUsers.ContainsKey(name))
                            {
                                dictUsers[name] = "-1";
                                response = GetGreetings();
                            }
                            break;
                        }
                    case EXIT_MENU:
                        {
                            response = ExitMenu(name);
                            break;
                        }
                    case BACK_MENU:
                        {
                            response = GetBackMenu(name, msg);
                            break;
                        }
                    case BACK_MAIN_MENU:
                        {
                            if (dictUsers.ContainsKey(name))
                            {
                                dictUsers[name] = "-1";
                            }
                            else
                            {
                                dictUsers.Add(name, "-1");
                            }
                            response = GetGreetings();
                            break;
                        }
                    default:
                        {
                            if (!dictUsers.ContainsKey(name))
                            {
                                dictUsers.Add(name, "-1");
                                response = GetGreetings();
                            }
                            else
                            {
                                if (EXIT_MENU.Equals(dictUsers[name]))
                                {
                                    try
                                    {
                                        StringBuilder sb = new StringBuilder();
                                        sb.AppendLine("");
                                        sb.AppendLine("留言已收到，我们会尽快处理的~");
                                        sb.AppendLine("若要再次查看导购菜单，请回复" + CUSTOM_MSG);
                                        sb.AppendLine("");
                                        response = sb.ToString();
                                        DateTime dataTime;
                                        DateTime.TryParse(time, out dataTime);
                                        time = dataTime.ToString("yyyy-MM-dd HH:mm:dd");
                                        AccessHelper.InsertCustomMsg(new CustomMsg() { ReceName = proc.Alias, Content = msg, Time = time, CustomName = name });
                                        dictUsers[name] = "-1";
                                    }
                                    catch { }
                                    break;
                                }
                                int index = 0;
                                bool flag = int.TryParse(msg, out index);
                                if (!flag)
                                {
                                    string[] cmds = dictUsers[name].Split(',');
                                    if (cmds.Length <= 1)
                                    {
                                        response = GetGreetings();
                                        int error;
                                        string resp;
                                        WriterError(name, out resp, out error);
                                        if (error == -1)
                                        {
                                            return resp;
                                        }
                                    }
                                    else
                                    {
                                        Node node = GetNode(Menu.Nodes, int.Parse(cmds[1]));
                                        for (int i = 2; i < cmds.Length; i++)
                                        {
                                            node = GetNode(node.SubNode, int.Parse(cmds[i]) - 1);
                                        }
                                        response = GetMenuMessage(node);
                                        int error;
                                        string resp;
                                        WriterError(name, out resp, out error);
                                        if (error == -1)
                                        {
                                            return resp;
                                        }

                                    }
                                    //返回当前菜单
                                    break;
                                }
                                else
                                {
                                    string cmd = dictUsers[name];// += "," + msg;
                                    if (cmd.Equals("-1"))
                                    {
                                        int count = GetChildCount(Menu.Nodes);
                                        if (index >= 1 && index <= count)
                                        {
                                            Node node = GetNode(Menu.Nodes, index);
                                            response = GetMenuMessage(node);
                                            dictUsers[name] += "," + msg;
                                            ClearErr(name);
                                        }
                                        else if (MenuId == index && DataFactory.SystemConfig.IsAutoAddQueryMenu)
                                        {
                                            response = QueryOrder(name);
                                        }
                                        else
                                        {
                                            int error;
                                            string resp;
                                            WriterError(name, out resp, out error);
                                            if (error == -1)
                                            {
                                                return resp;
                                            }
                                            //错误菜单时返回当前菜单
                                            response = GetGreetings();
                                        }
                                    }
                                    else
                                    {
                                        string tempCmd = dictUsers[name];
                                        string[] cmds = tempCmd.Split(',');
                                        Node node = GetNode(Menu.Nodes, int.Parse(cmds[1]));
                                        Node temp = GetParentNode(node, cmds);
                                        int count = GetChildCount(temp.SubNode);
                                        if (index >= 1 && index <= count)
                                        {
                                            //count = GetChildCount(temp.SubNode[index-1]);
                                            //if(count>0)
                                            int tempIndex = CheckIndex(temp) + index;
                                            if (tempIndex != index - 1)
                                            {
                                                dictUsers[name] += "," + tempIndex;
                                                response = GetMenuMessage(temp.SubNode[tempIndex - 1]);
                                                ClearErr(name);
                                            }
                                            else
                                            {
                                                dictUsers[name] += "," + msg;
                                                response = GetMenuMessage(temp.SubNode[index - 1]);
                                            }
                                        }
                                        else
                                        {
                                            response = GetMenuMessage(temp);
                                            int error;
                                            string resp;
                                            WriterError(name, out resp, out error);
                                            if (error == -1)
                                                return resp;
                                        }
                                    }
                                }
                            }
                            break;
                        }
                }
                #endregion
            }
            catch
            {
                return GetBackMenu(name, msg);
            }
            if (string.IsNullOrEmpty(response))
            {
                response = GetGreetings();
            }
            return response;
        }

        void ClearErr(string name) {
            if (dictUsersError.ContainsKey(name))
            {
                dictUsersError[name] = 0;
            }
        }

        string Exit(string name)
        {
            if (dictUsers.ContainsKey(name))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("");
                sb.AppendLine("您好,由于您连续三次回复错误,已经退出自动导购.若要留言，请继续回复！若要再次查看导购菜单，请回复321");
                sb.AppendLine("");
                if (dictUsers.ContainsKey(name)) {
                    dictUsers[name] = EXIT_MENU.ToString();
                }
                if (dictUsersError.ContainsKey(name))
                {
                    dictUsersError.Remove(name);
                }
                return sb.ToString();
            }
            return string.Empty;
        }

        void WriterError(string name, out string response, out int error)
        {
            error = 0;
            response = string.Empty;
            if (DataFactory.SystemConfig.IsSeriesThreeError)
            {
                if (!dictUsersError.ContainsKey(name))
                {
                    dictUsersError.Add(name, 2);
                }
                else
                {
                    if (dictUsersError[name] >= 3)
                    {
                        error = -1;
                        response = Exit(name);
                        return;
                    }
                    dictUsersError[name] += 1;
                }
            }
        }

        TaobaoHelper taobaoHelper;

        string QueryOrder(string name)
        {
            if (taobaoHelper == null)
            {
                lock (this)
                {
                    try
                    {
                        if (taobaoHelper == null)
                        {
                            var ds = from temp in DataFactory.Accounts where temp.AccountId.Equals(proc.Alias) select temp;
                            Account account = ds.FirstOrDefault();
                            if (account != null)
                            {
                                taobaoHelper = new TaobaoHelper(account);
                            }
                            else
                            {
                                ds = from temp in DataFactory.Accounts where temp.Default select temp;
                                account = ds.FirstOrDefault();
                                if (account != null)
                                {
                                    taobaoHelper = new TaobaoHelper(account);
                                }
                            }
                        }
                    }
                    catch { }
                }
            }

            if (taobaoHelper != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("子菜单:查件");
                sb.AppendLine("----------------------------------------");
                string msg = taobaoHelper.FindOrderTrack(name);
                if (string.IsNullOrEmpty(msg))
                {
                    sb.AppendLine(DataFactory.SystemConfig.NotQuerySalutation);
                }
                else
                {
                    sb.AppendLine(msg);
                }
                sb.AppendLine("----------------------------------------");
                sb.AppendLine("回复0返回上一级菜单");
                sb.AppendLine("回复123退出菜单（之后可以给我留言哦）");
                return sb.ToString();
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("子菜单:查件");
                sb.AppendLine("----------------------------------------");
                sb.AppendLine("店铺还没设置“数字钥匙”，无法进行“自动查件”，麻烦您提醒本店人工客服哦。");
                sb.AppendLine("----------------------------------------");
                sb.AppendLine("回复0返回上一级菜单");
                sb.AppendLine("回复123退出菜单（之后可以给我留言哦");
                return sb.ToString();
            }
        }

        int CheckIndex(Node node)
        {
            int index = 0;
            foreach (var d in node.SubNode)
            {
                if (d.SubNode.Count > 0)
                {
                    break;
                }
                index++;
            }
            return index;
        }

        Node GetParentNode(Node node, string[] cmds)
        {
            for (int i = 2; i < cmds.Length; i++)
            {
                node = GetNode(node.SubNode, int.Parse(cmds[i]) - 1);
            }
            return node;
        }

        int GetChildCount(List<Node> nodes)
        {
            int count = 0;
            foreach (var msg in nodes)
            {
                if (msg.SubNode.Count > 0)
                {
                    count++;
                }
            }
            return count;
        }

        string GetMenuMessage(Node node)
        {
            
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(string.Format("子菜单： [{0}]", node.Text));
            sb.AppendLine("------------------------------------------");
            sb.AppendLine("");
            int id = 1;
            bool flag = false;
            foreach (var msg in node.SubNode)
            {
                if (msg.SubNode.Count > 0)
                {
                    SetContent(id, msg.Text, sb);
                    id++;
                    flag = true;
                }
                else
                {
                    sb.AppendLine("。" + msg.Text);
                }
            }
            if (flag)
                setBottomMsg("1", (id - 1) == 0 ? "1" : (id - 1).ToString(),true, sb);
            else
                setBottomMsg1(sb);
            return sb.ToString();
        }

        Node GetNode(List<Node> nodes, int index)
        {
            return nodes.ElementAt(index);
        }

        string GetMenuItem(string msg)
        {
            StringBuilder sb = new StringBuilder();


            return sb.ToString();
        }

        string GetGreetings()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("主菜单");
            sb.AppendLine("------------------------------------------");
            sb.AppendLine();
            int id = 1;
            foreach (var msg in Menu.Nodes)
            {
                if (msg.SubNode.Count > 0)
                {
                    SetContent(id, msg.Text, sb);
                    id++;
                }
                else
                {
                    if (DataFactory.SystemConfig.IsAutoAddQueryMenu && msg.Text.Equals("查件"))
                    {
                        MenuId = id;
                        SetContent(id, msg.Text, sb);
                        id++;
                    }
                    else
                    {
                        sb.AppendLine("。" + msg.Text);
                    }
                }
            }
            setBottomMsg("1", (id - 1) == 0 ? "1" : (id - 1).ToString(), false, sb);
            return sb.ToString();
        }

        void SetContent(int id, string text, StringBuilder sb)
        {
            if (DataFactory.SystemConfig.IsMenuGuideNewLine)
            {
                sb.AppendLine(string.Format("[{0}]{1}", id, text));
            }
            else {
                sb.Append(string.Format("[{0}]{1}", id, text));
            }
        }

        void setBottomMsg(string start, string end, bool isback, StringBuilder sb)
        {
            sb.AppendLine("");
            sb.AppendLine("------------------------------------------");
            sb.AppendLine(string.Format("回复{0}~{1}之间的数字，选择一个菜单项", start, end));
            if (isback)
            {
                sb.AppendLine("回复0返回上一级菜单");
            }
            sb.AppendLine("回复100返回主菜单");
            sb.AppendLine("回复123退出菜单");
            sb.AppendLine("");
        }

        void setBottomMsg1(StringBuilder sb)
        {
            sb.AppendLine("");
            sb.AppendLine("------------------------------------------");
            sb.AppendLine("回复0返回上一级菜单");
            sb.AppendLine("回复100返回主菜单");
            sb.AppendLine("回复123退出菜单");
            sb.AppendLine("");
        }
    }
}